import React, { useState, useRef } from 'react';
import { View, Text, Modal, TouchableOpacity, Alert, Dimensions } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import SignatureScreen from 'react-native-signature-canvas';

interface HandwrittenSignatureProps {
  visible: boolean;
  onClose: () => void;
  onSave: (signatureData: string) => void;
}

const HandwrittenSignature: React.FC<HandwrittenSignatureProps> = ({
  visible,
  onClose,
  onSave
}) => {
  // 创建签名画板引用
  const signatureRef = useRef<any>(null);
  // 添加横向/竖向模式状态
  const [isLandscape, setIsLandscape] = useState(false);
  
  // 处理签名完成
  const handleSignature = (signature: string) => {
    console.log('签名完成，数据长度:', signature ? signature.length : 0);
    if (signature && signature.length > 100) {
      onSave(signature);
    } else {
      Alert.alert('提示', '请先进行有效的签名');
    }
  };
  
  // 切换横向/竖向模式
  const toggleOrientation = () => {
    setIsLandscape(!isLandscape);
    // 清除当前签名
    if (signatureRef.current) {
      signatureRef.current.clearSignature();
    }
  };
  
  // 根据当前模式获取不同的样式
  const getWebStyle = () => {
    return `
      body, html {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
        overflow: hidden;
      }
      .m-signature-pad {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
        position: relative;
      }
      .m-signature-pad--body {
        width: 100%;
        height: calc(100% - 60px);
      }
      .m-signature-pad--footer {
        display: flex;
        justify-content: space-between;
        height: 60px;
        background-color: rgba(255, 255, 255, 0.9);
        padding: 10px;
      }
      .save, .clear {
        font-size: 16px;
        padding: 10px 20px;
        border-radius: 5px;
        border: none;
        color: white;
        font-weight: bold;
        text-transform: none;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        z-index: 100;
      }
      .save {
        background-color: #3B82F6;
      }
      .clear {
        background-color: #EF4444;
      }
    `;
  };
  
  // 根据横竖屏获取正确的宽高
  const { width, height } = Dimensions.get('window');
  // 限制签名区域尺寸，确保按钮可见
  const signatureWidth = isLandscape ? Math.min(height, width * 1.5) : width;
  const signatureHeight = isLandscape ? Math.min(width * 0.8, height * 0.6) : height * 0.7;
  
  return (
    <Modal
      visible={visible}
      transparent={false}
      animationType="slide"
      onRequestClose={onClose}
    >
      <View className="flex-1 bg-white">
        <View className="p-4 flex-row justify-between items-center border-b border-gray-200 z-10">
          <TouchableOpacity 
            onPress={onClose}
            className="p-2"
          >
            <Ionicons name="close" size={24} color="#6B7280" />
          </TouchableOpacity>
          <Text className="text-lg font-bold">手写签名</Text>
          <TouchableOpacity 
            onPress={toggleOrientation}
            className="p-2 z-20"
          >
            <Ionicons 
              name={isLandscape ? "phone-portrait" : "phone-landscape"} 
              size={24} 
              color="#6B7280" 
            />
          </TouchableOpacity>
        </View>
        
        <View className="flex-1 bg-gray-50 items-center justify-center">
          {isLandscape ? (
            // 横向模式
            <View style={{ 
              width: signatureWidth,
              height: signatureHeight,
              transform: [{ rotate: '90deg' }],
              overflow: 'visible',
              marginVertical: 50 // 增加上下边距，确保按钮可见
            }}>
              <SignatureScreen
                ref={signatureRef}
                onOK={handleSignature}
                onEmpty={() => Alert.alert('提示', '请先进行签名')}
                webStyle={getWebStyle()}
                descriptionText="在此处签名"
                clearText="清除"
                confirmText="保存" 
                autoClear={false}
                imageType="image/png"
                backgroundColor="transparent"
                penColor="black"
                dotSize={2}
                minWidth={2}
                maxWidth={5}
              />
            </View>
          ) : (
            // 竖向模式
            <View style={{ 
              width: signatureWidth,
              height: signatureHeight
            }}>
              <SignatureScreen
                ref={signatureRef}
                onOK={handleSignature}
                onEmpty={() => Alert.alert('提示', '请先进行签名')}
                webStyle={getWebStyle()}
                descriptionText="在此处签名"
                clearText="清除"
                confirmText="保存"
                autoClear={false}
                imageType="image/png"
                backgroundColor="transparent"
                penColor="black"
                dotSize={2}
                minWidth={2}
                maxWidth={5}
              />
            </View>
          )}
        </View>
        
        {/* 底部说明文字 */}
        <View className="p-4 bg-white z-10">
          <Text className="text-gray-500 text-center">请在上方区域手写您的签名</Text>
          <Text className="text-gray-500 text-center mb-2">完成后点击"保存"按钮</Text>
          <Text className="text-gray-500 text-center mb-2">点击{isLandscape ? "竖向" : "横向"}按钮可切换签名方向</Text>
        </View>
      </View>
    </Modal>
  );
};

export default HandwrittenSignature;